class Wxpay::PaymentNotificationsController < ApplicationController

  SUCCESS_RESPONSE = <<-XML.strip.freeze
    <xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>
  XML

  SIGNATURE_ERROR_RESPONSE = <<-XML.strip.freeze
    <xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>
  XML

  def create
    raw_content = request.body.read
    notification_params = Hash.from_xml(raw_content)['xml'].with_indifferent_access
    return render text: SIGNATURE_ERROR_RESPONSE, status: :unprocessable_entity, content_type: 'application/xml; charset=utf-8' unless WxPay::Sign.verify?(notification_params)
    order = Order.find_by(order_num: notification_params[:out_trade_no])
    PaymentNotification.create(order_history_id: order.id, payment_method: 'wxpay', raw_content: raw_content, request_id: request.request_id)
    send(:"on_#{notification_params[:result_code].downcase}", order, notification_params)
    # TODO notify mobile through websocket
    render text: SUCCESS_RESPONSE, content_type: 'application/xml; charset=utf-8'
  end

  private

  def on_success(order, params)
    # expire_cache "orders:#{order.payer.id}:index:*", "orders:#{order.payer.id}:#{order.id}" do
      order.confirm(params[:transaction_id], params[:openid]) unless order.succeeded?
    # end
  end

  def on_fail(order, *)
    # expire_cache "orders:#{order.payer.id}:index:*", "orders:#{order.payer.id}:#{order.id}" do
      order.reject unless order.succeeded?
    # end
  end

end
